package pl.edu.agh.iosr.gamblingzone.model;

import java.util.Calendar;
import java.util.HashSet;
import java.util.Set;
import java.util.List;

import javax.persistence.AttributeOverride;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Inheritance;
import javax.persistence.InheritanceType;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToMany;
import javax.persistence.ManyToOne;

/**
 * The Class Bet.
 * 
 * 
 * @author maciej
 */
@AttributeOverride(name="id",
		column=@Column(name="BET_ID"))
@Entity(name="BETS")
@Inheritance(strategy = InheritanceType.JOINED)
public class Bet extends EntityModel{
	
	/** The Constant serialVersionUID. */
	private static final long serialVersionUID = -4075061622480169726L;

	/** The betting slip. */
	@ManyToOne(targetEntity=BettingSlip.class)
	@JoinColumn(name="BETTING_SLIP_ID", nullable=false)
	private BettingSlip bettingSlip;
	
	/** The participant. */
	@ManyToOne
	@JoinColumn(name="WINNER_ID", nullable=false)
	private Participant winner;
	
	@ManyToMany(fetch=FetchType.EAGER)
	private Set<AbstractEvent> events = new HashSet<AbstractEvent>();

	/**
	 * Gets the betting slip.
	 * 
	 * @return the betting slip
	 */
	public BettingSlip getBettingSlip() {
		return bettingSlip;
	}

	/**
	 * Sets the betting slip.
	 * 
	 * @param bettingSlip the new betting slip
	 */
	protected void setBettingSlip(BettingSlip bettingSlip) {
		this.bettingSlip = bettingSlip;
	}

	/**
	 * Gets the participant.
	 * 
	 * @return the participant
	 */
	public Participant getWinner() {
		return winner;
	}

	/**
	 * Sets the participant.
	 * 
	 * @param participant the new participant
	 */
	public void setWinner(Participant participant) {
		this.winner = participant;
	}
	
	public Set<AbstractEvent> getEvents() {
		return events;
	}
	
	public void addEvent(AbstractEvent abstractEvent) {
		events.add(abstractEvent);
	}
	
	public boolean isWinning() {
		boolean result = true;
		
		for (AbstractEvent event : events) {
			if(!winner.equals(event.getWinner())) {
				result = false;
				break;
			}
		}
		
		return result;
	}
	
	public boolean isClosed() {
		boolean result = true;
		Calendar today = Calendar.getInstance();
		Calendar closingDate = Calendar.getInstance();
		
		for (AbstractEvent event: events) {
			closingDate.setTime(event.getClosingDate());
			if(today.before(closingDate)){
				result = false;
				break;
			}
		}
		
		return result;
	}
}
